package core.servlets;

import static core.util.StoredData.storedSessionData;
import static core.util.Utilities.COOKIE_NAME;
import static core.util.Utilities.redirectPage;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jdt.core.compiler.InvalidInputException;

import core.util.MyCookieValue;
import core.util.UserSessionData;

public class ReplaceServlet extends HttpServlet
{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet( HttpServletRequest request,
            HttpServletResponse response ) throws ServletException, IOException {

        Cookie[] cookies = request.getCookies();
        MyCookieValue cookieValue = null;
        // get our cookie
        Cookie cookie = null;
        if( cookies != null ) {
            for( Cookie c : cookies ) {
                cookie = c;
                if( COOKIE_NAME.equalsIgnoreCase( cookie.getName() ) ) {
                    try {
                        cookieValue = new MyCookieValue( cookie.getValue() );
                        break;
                    } catch( InvalidInputException e ) {
                        e.printStackTrace();
                        throw new ServletException( e );
                    }
                }
            }
        } else {
            return;
        }

        String sessionId = null;
        if( cookieValue != null ) {
            sessionId = cookieValue.getSessionId();
        } else {
            return;
        }

        if( sessionId != null && storedSessionData.containsKey( sessionId ) ) {
            // get param names
            @SuppressWarnings("rawtypes")
            Enumeration paramNames = request.getParameterNames();

            String newText = null;
            while( paramNames.hasMoreElements() ) {
                String paramName = (String) paramNames.nextElement();
                String[] paramValues = request.getParameterValues( paramName );
                if( "NewText".equalsIgnoreCase( paramName ) ) {
                    newText = paramValues[0];
                    break;
                }
            }

            storedSessionData.put( sessionId, new UserSessionData( 0, newText,
                    cookieValue ) );
        } else {
            return;
        }

        redirectPage( response, "home" );
    }
}
